import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';
import { ModelType } from '@typegoose/typegoose/lib/types';
import IP2Region, { IP2RegionResult } from "ip2region";
import { InjectModel } from 'nestjs-typegoose';
import { Observable } from 'rxjs';

@Injectable()
export class WorkInterceptor implements NestInterceptor {

  constructor(
    @InjectModel(QudaobaoModel) private readonly qudaobao: ModelType<QudaobaoModel>,
  ) { }

  async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
    const req = context.switchToHttp().getRequest();
    req.isProvince = true
    /* 获取ip位置 */
    const channelResult = await this.qudaobao.findOne({ mark: req.dns }, 'qidu')
    if (channelResult) {
      if (channelResult.qidu) {
        const ipInstance = new IP2Region({ disableIpv6: false });
        const ipdetails: IP2RegionResult = ipInstance.search(this.getip(req));
        const cs = ipdetails.province + ipdetails.city
        const cityList = channelResult.qidu.split(',')
        for (let i = 0; i < cityList.length; i++) {
          const regProvince = new RegExp(cityList[i]);
          if (cs.match(regProvince)) {
            req.isProvince = false
          }
        }
      }
    }
    return next.handle()
  }

  public getip(req): string {
    try {
      return (req.headers['x-wq-realip'] ||
        req.headers['X-Real-IP'] ||
        req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress ||
        req.ip).match(/\d+.\d+.\d+.\d+/)[0]
    } catch (e) {
      return "未知IP";
    }
  }
}
